# 让登入支持手机号
from django.contrib.auth.backends import ModelBackend
import re

from user.models import User


def jwt_response_payload_handler(token, user, request):
    return {
        "token": token,
        "user_id": user.id,
        "role":[sign.get("sign") for sign in user.role.all().values("sign")]
    }


def get_user_by_account(phone):
    if re.match(r"^1\d{10}$", phone):
        user = User.objects.filter(phone=phone,is_deleted='0').first()
        sign_list = [sign.get("sign") for sign in user.role.all().values("sign")]
        if '2' in sign_list or '3' in sign_list:
            return user
        return None
    return None


class UsernameMobileAuthBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, phone=None):
        user = get_user_by_account(phone)
        # 判断也用户是否存在，并且同时判断用户的密码是否正确
        # 在用户的模型类由于继承了AbstractUser,这个是AbstractUser自带的密码认证
        if user and user.check_password(password):
            return user
